local extension = Package("ling11")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

local bianque = General(extension, "lingling__bianque", "qun", 3)
local miaoshou = fk.CreateActiveSkill{
  name = "lingling__miaoshou",
  anim_type = "support",
  prompt = "#lingling__miaoshou",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, player, to_select, selected, targets)
    return #selected == 0 and table.contains(player:getCardIds("h"), to_select) and
      not player:prohibitDiscard(to_select)
  end,
  target_filter = function(self, to_select, selected, cards)
    return #selected == 0 and Fk:currentRoom():getPlayerById(to_select):isWounded()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    if target:isWounded() and not target.dead then
      room:recover{
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    end
    if not target.dead and math.random() < 0.25 then
      room:changeMaxHp(target, 1)
    end
  end,
}
local huanxin = fk.CreateActiveSkill{
  name = "lingling__huanxin",
  anim_type = "control",
  frequency = Skill.Limited,
  prompt = "#lingling__huanxin",
  card_num = 0,
  target_num = 2,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, cards)
    return #selected < 2 and to_select ~= player.id
  end,
  on_use = function(self, room, effect)
    room:sortPlayersByAction(effect.tos)
    local target = table.map(effect.tos, Util.Id2PlayerMapper)
    local skills = {{}, {}}
    for i = 1, 2, 1 do
      for _, skill in ipairs(target[i].player_skills) do
        if skill:isPlayerSkill(target[i]) and skill.visible and
          not table.contains({"m_feiyang", "m_bahu"}, skill.name) and
          not skill.name:startsWith("lingling_lord__") then
          table.insertIfNeed(skills[i], skill.name)
        end
      end
    end
    room:handleAddLoseSkills(target[1], "-"..table.concat(skills[1], "|-").."|"..table.concat(skills[2], "|"), nil, true, false)
    room:handleAddLoseSkills(target[2], "-"..table.concat(skills[2], "|-").."|"..table.concat(skills[1], "|"), nil, true, false)
  end,
}
local huihun = fk.CreateActiveSkill{
  name = "lingling__huihun",
  anim_type = "support",
  frequency = Skill.Limited,
  prompt = "#lingling__huihun",
  interaction = function()
    local choices = {}
    local players = Fk:currentRoom().players
    for i = 1, #players, 1 do
      if players[i].dead then
        table.insert(choices, "lingling__huihun_choice:::"..players[i].seat..":"..players[i].general)
      end
    end
    if #choices > 0 then
      return UI.ComboBox { choices = choices }
    end
  end,
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
      table.find(Fk:currentRoom().players, function (p)
        return p.dead
      end)
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = table.find(room.players, function (p)
      return p.seat == tonumber(string.split(self.interaction.data, ":")[4])
    end)
    if target == nil then return end
    room:doIndicate(player.id, {target.id})
    room:revivePlayer(target, true)
    target.hp = math.min(2, target.maxHp)
    room:broadcastProperty(target, "hp")
    target:drawCards(4, self.name)
  end,
}
local huihun_trigger = fk.CreateTriggerSkill{
  name = "#lingling__huihun_trigger",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(huihun) and player:usedSkillTimes("lingling__huihun", Player.HistoryGame) == 0 and
      player:isWounded() and math.random() < 0.5
  end,
  on_use = function (self, event, target, player, data)
    player.room:recover{
      who = player,
      num = 1,
      recoverBy = player,
      skillName = "lingling__huihun",
    }
  end,
}
huihun:addRelatedSkill(huihun_trigger)
bianque:addSkill(miaoshou)
bianque:addSkill(huanxin)
bianque:addSkill(huihun)
Fk:loadTranslationTable{
  ["lingling__bianque"] = "扁鹊",
  ["#lingling__bianque"] = "上古神医",
  ["illustrator:lingling__bianque"] = "珊瑚虫",
  ["designer:lingling__bianque"] = "伶",

  ["lingling__miaoshou"] = "妙手",
  [":lingling__miaoshou"] = "出牌阶段限一次，你可以弃置一张手牌并令一名受伤角色回复1点体力，然后其有25%几率加1点体力上限。",
  ["lingling__huanxin"] = "换心",
  [":lingling__huanxin"] = "限定技，出牌阶段，你可以令两名其他角色交换所有技能。",
  ["lingling__huihun"] = "回魂",
  [":lingling__huihun"] = "限定技，出牌阶段，你可以令一名已死亡的角色复活，其回复体力至2点，摸牌至四张。回合开始时，若你未发动过此技能，"..
  "你有50%几率回复1点体力。"..
  "<br><br> <font color = '#a40000'>扁鹊言医，为方者宗。",
  ["#lingling__miaoshou"] = "妙手：你可以弃一张手牌令一名角色回复1点体力，其有25%几率加1点体力上限",
  ["#lingling__huanxin"] = "换心：你可以令两名角色交换所有技能！",
  ["#lingling__huihun"] = "回魂：令一名已死亡角色复活！回复体力至2点，摸牌至四张",
  ["lingling__huihun_choice"] = "复活%arg号位 %arg2",
  ["#lingling__huihun_trigger"] = "回魂",

  ["$lingling__huanxin1"] = "人性乃天生，我亦能再造。",
  ["$lingling__huanxin2"] = "一人气弱身强，一人身弱气强，换心即可。",
  ["$lingling__huihun1"] = "此尸厥也，乃假死，非真死。",
  ["$lingling__huihun2"] = "阳主上主表，阴主下主里，阴阳和合，方可无虞。",
}

local xuanzang = General(extension, "lingling__xuanzang", "tang", 3)
local chanwu = fk.CreateTriggerSkill{
  name = "lingling__chanwu",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.ChainStateChanged, fk.TurnedOver, fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.ChainStateChanged or event == fk.TurnedOver then
        return target == player
      elseif event == fk.DamageCaused then
        return target and target ~= player and data.to == player and
          ((player.chained and not target.chained) or
          (not player.chained and target.chained) or
          (player.faceup and not target.faceup) or
          (not player.faceup and target.faceup))
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.ChainStateChanged or event == fk.TurnedOver then
      room:notifySkillInvoked(player, self.name, "drawcard")
      player:drawCards(2, self.name)
    elseif event == fk.DamageCaused then
      room:notifySkillInvoked(player, self.name, "defensive")
      if target.dead then
        return true
      else
        local chained = (player.chained and not target.chained) or (not player.chained and target.chained)
        local TurnedOver = (player.faceup and not target.faceup) or (not player.faceup and target.faceup)
        if (chained or TurnedOver) and room:askForSkillInvoke(target, self.name, nil, "#lingling__chanwu-choice:"..player.id) then
          if player.chained and not target.chained then
            target:setChainState(true)
          elseif not player.chained and target.chained then
            target:setChainState(false)
          end
          if target.dead then return end
          if TurnedOver then
            target:turnOver()
          end
          return
        end
        return true
      end
    end
  end,
}
local xixing = fk.CreateTriggerSkill{
  name = "lingling__xixing",
  switch_skill_name = "lingling__xixing",
  anim_type = "switch",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player:getSwitchSkillState(self.name, false) == fk.SwitchYang then
        return not player.chained
      else
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if player:getSwitchSkillState(self.name, false) == fk.SwitchYang then
      return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__xixing-yang")
    else
      return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__xixing-yin")
    end
  end,
  on_use = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@lingling__xixing", 1)
    if player:getSwitchSkillState(self.name, true) == fk.SwitchYang then
      player:setChainState(true)
    else
      player:turnOver()
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("@@lingling__xixing") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@lingling__xixing", 0)
  end,
}
local xixing_trigger = fk.CreateTriggerSkill{
  name = "#lingling__xixing_trigger",
  anim_type = "drawcard",
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return target ~= player and player:getMark("@@lingling__xixing") > 0 and
      table.every(player.room.alive_players, function (p)
        return target:distanceTo(player) >= target:distanceTo(p)
      end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
    local rand, n = 0.5, 1
    if room:askForSkillInvoke(player, "lingling__xixing", nil, "#lingling__xixing-damage") then
      room:damage{
        to = player,
        damage = 1,
        damageType = fk.ThunderDamage,
        skillName = "lingling__xixing",
      }
      if player.dead then return end
      rand, n = 0.8, 2
    end
    if math.random() < rand then
      local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick", n)
      if #cards > 0 then
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, "lingling__xixing", nil, false, player.id)
      end
    end
  end,
}
xixing:addRelatedSkill(xixing_trigger)
xuanzang:addSkill(chanwu)
xuanzang:addSkill(xixing)
Fk:loadTranslationTable{
  ["lingling__xuanzang"] = "玄奘",
  ["#lingling__xuanzang"] = "唐僧",
  ["illustrator:lingling__xuanzang"] = "珊瑚虫",
  ["designer:lingling__xuanzang"] = "伶",

  ["lingling__chanwu"] = "禅悟",
  [":lingling__chanwu"] = "当你武将牌状态改变后，你摸两张牌。当其他角色对你造成伤害时，其须将武将牌状态变为与你相同，否则防止此伤害。",
  ["lingling__xixing"] = "西行",
  [":lingling__xixing"] = "转换技，回合结束时，你可以①横置②翻面，然后与你距离最远的角色回合开始时，你有50%几率随机获得一张锦囊牌，"..
  "你可以受到1点雷电伤害，将此次几率变成80%且此次获得张数改为两张。"..
  "<br><br> <font color = '#a40000'>月满一江水，前世莫追。",
  ["#lingling__chanwu-choice"] = "禅悟：将武将牌状态变为与 %src 相同，或点“取消”防止你对其造成的伤害",
  ["#lingling__xixing-yang"] = "西行：是否横置？",
  ["#lingling__xixing-yin"] = "西行：是否翻面？",
  ["@@lingling__xixing"] = "西行",
  ["#lingling__xixing_trigger"] = "西行",
  ["#lingling__xixing-damage"] = "西行：你有50%几率获得一张锦囊牌，是否受到1点雷电伤害，改为概率80%且获得两张？",
}

local dharma = General(extension, "lingling__dharma", "qun", 5)
local mianbi = fk.CreateTriggerSkill{
  name = "lingling__mianbi",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.GameStart, fk.EventPhaseChanging},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.GameStart then
        return true
      elseif event == fk.EventPhaseChanging then
        return target == player and data.to == Player.Judge
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    if event == fk.GameStart then
      math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
      player:drawCards(3, self.name)
      if not player.dead then
        player:turnOver()
      end
    elseif event == fk.EventPhaseChanging then
      return true
    end
  end,
}
local wuxiang = fk.CreateTriggerSkill{
  name = "lingling__wuxiang",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card.trueName == "slash" then
      self.cost_data = {}
      local targets = {}
      for _, id in ipairs(TargetGroup:getRealTargets(data.tos)) do
        local p = player.room:getPlayerById(id)
        if (not data.damageDealt or not data.damageDealt[id]) and not p.dead and #p:getEquipments(Card.SubtypeArmor) > 0 then
          if #player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function (e)
            local use = e.data[1]
            return use.from == player.id and use.card.trueName == "slash" and
              table.contains(TargetGroup:getRealTargets(use.tos), id) and
              (not use.damageDealt or not use.damageDealt[id])
          end, Player.HistoryTurn) == 2 then
            table.insertIfNeed(targets, id)
          end
        end
      end
      if #targets > 0 then
        self.cost_data = {tos = targets}
      end
      if math.random() < 0.5 then
        self.cost_data.choice = 2
      end
      if next(self.cost_data) then
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data and self.cost_data.tos and #self.cost_data.tos > 0 then
      local tos = table.simpleClone(self.cost_data.tos)
      room:sortPlayersByAction(tos)
      for _, id in ipairs(tos) do
        local p = room:getPlayerById(id)
        if not p.dead then
          local ids = p:getEquipments(Card.SubtypeArmor)
          if #ids > 0 then
            room:moveCardTo(ids, Card.Void, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
            room:sendLog{
              type = "#destructDerivedCards",
              card = ids,
            }
          end
        end
      end
    end
    if self.cost_data and self.cost_data.choice and not player.dead and not player:prohibitUse(Fk:cloneCard("slash")) then
      U.askForUseVirtualCard(room, player, "slash", nil, self.name, "#lingling__wuxiang-slash", true, true, false, true)
    end
  end,
}
dharma:addSkill(mianbi)
dharma:addSkill(wuxiang)
Fk:loadTranslationTable{
  ["lingling__dharma"] = "达摩",
  ["#lingling__dharma"] = "一苇渡江",
  ["illustrator:lingling__dharma"] = "珊瑚虫",
  ["designer:lingling__dharma"] = "伶",

  ["lingling__mianbi"] = "面壁",
  [":lingling__mianbi"] = "游戏开始时，你摸三张牌并翻面。你跳过判定阶段。",
  ["lingling__wuxiang"] = "无相",
  [":lingling__wuxiang"] = "当你使用【杀】结算后，有50%几率再视为使用一张无次数限制的【杀】。一回合内你使用【杀】对同一目标未造成伤害两次后，"..
  "销毁其装备区的防具牌。"..
  "<br><br> <font color = '#a40000'>眼不见，心不乱，寻常修为。<br>入一切相，破一切相，方得自在。",
  ["#lingling__wuxiang-slash"] = "无相：你可以视为使用一张无次数限制的【杀】",
}

local kongqiu = General(extension, "lingling__kongqiu", "qun", 3)
local youjiaowulei = fk.CreateTriggerSkill{
  name = "lingling__youjiaowulei",
  anim_type = "support",
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if target == player then
        return #player.room:getOtherPlayers(player) > 0
      else
        return true
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if target == player then
      return true
    else
      return player.room:askForSkillInvoke(target, self.name, nil, "#lingling__youjiaowulei-invoke:"..player.id)
    end
  end,
  on_use = function (self, event, target, player, data)
    if target == player then
      local room = player.room
      room:doIndicate(player.id, table.map(room:getOtherPlayers(player), Util.IdMapper))
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if not p.dead then
          p:drawCards(1, self.name)
        end
      end
    else
      player:drawCards(1, self.name)
    end
  end,
}
local zhouyou = fk.CreateTriggerSkill{
  name = "lingling__zhouyou",
  anim_type = "control",
  events = {fk.BeforeTurnStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and #player.room:getOtherPlayers(player) > 0
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
      "#lingling__zhouyou-choose", self.name, true)
    if #to > 0 then
      self.cost_data = {tos = to}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:setPlayerMark(player, self.name, to.id)
    room:setPlayerMark(player, "@lingling__zhouyou", to.general)
    local skills = {}
    for _, skill in ipairs(to.player_skills) do
      if skill:isPlayerSkill(to) and skill.visible and not player:hasSkill(skill, true) then
        table.insertIfNeed(skills, skill.name)
      end
    end
    if #skills > 0 then
      room:setPlayerMark(player, "lingling__zhouyou_skills-turn", skills)
      room:handleAddLoseSkills(player, skills, nil, true, false)
    end
  end,

  refresh_events = {fk.BeforeTurnStart, fk.AfterTurnEnd},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(self.name) ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeTurnStart then
      room:setPlayerMark(player, self.name, 0)
      room:setPlayerMark(player, "@lingling__zhouyou", 0)
    elseif event == fk.AfterTurnEnd then
      local skills = player:getTableMark("lingling__zhouyou_skills-turn")
      if #skills > 0 then
        room:handleAddLoseSkills(player, "-"..table.concat(skills, "|-"), nil, true, false)
      end
    end
  end,
}
local zhouyou_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhouyou_delay",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:getMark("lingling__zhouyou") ~= 0 and
      not player.room:getPlayerById(player:getMark("lingling__zhouyou")).dead and
      math.random() < 0.6
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(player:getMark("lingling__zhouyou"))
    room:damage{
      to = to,
      damage = data.damage,
      damageType = data.damageType,
      skillName = "lingling__zhouyou",
    }
  end,
}
zhouyou:addRelatedSkill(zhouyou_delay)
kongqiu:addSkill(youjiaowulei)
kongqiu:addSkill(zhouyou)
Fk:loadTranslationTable{
  ["lingling__kongqiu"] = "孔子",
  ["#lingling__kongqiu"] = "道德之祖",
  ["illustrator:lingling__kongqiu"] = "珊瑚虫",
  ["designer:lingling__kongqiu"] = "伶",

  ["lingling__youjiaowulei"] = "有教无类",
  [":lingling__youjiaowulei"] = "回合开始时，所有其他角色各摸一张牌。其他角色回合开始时，其可以令你摸一张牌。",
  ["lingling__zhouyou"] = "周游",
  [":lingling__zhouyou"] = "回合开始前，你可以选择一名其他角色，本回合你视为拥有其所有技能。直到你下回合开始，当你受到伤害后，"..
  "其有60%几率受到等量的伤害。"..
  "<br><br> <font color = '#a40000'>大道畅行，天下为公。",
  ["#lingling__youjiaowulei-invoke"] = "有教无类：是否令 %src 摸一张牌？",
  ["#lingling__zhouyou-choose"] = "周游：你可以选择一名角色，本回合视为拥有其技能，当你受到伤害后其有几率受到等量伤害",
  ["@lingling__zhouyou"] = "周游",
  ["#lingling__zhouyou_delay"] = "周游",
}

Fk:loadTranslationTable{
  ["lingling__wangxizhi"] = "王羲之",
  ["#lingling__wangxizhi"] = "手书无愧",
  ["illustrator:lingling__wangxizhi"] = "珊瑚虫",
  ["designer:lingling__wangxizhi"] = "伶",

  ["lingling__linmo"] = "临摹",
  [":lingling__linmo"] = "转换技，每回合限一次，①出牌阶段，你可以记录一名角色的所有手牌。②当你造成或受到伤害后，你可以弃置所有手牌，"..
  "然后创造、获得你上一次记录的所有牌，这些牌进入弃牌堆时销毁。",
  ["lingling__miaobi"] = "妙笔",
  [":lingling__miaobi"] = "当你不因此技能获得牌后，你有40%几率将获得牌中随机一至X张牌随机更换为当前牌堆没有的牌（X为你获得的牌数）。"..
  "若你因此更换了所有手牌，你获得技能〖我道〗。",
  ["lingling__wodao"] = "我道",
  [":lingling__wodao"] = "出牌阶段限一次，你可以从随机三张当前牌堆没有的牌中选择一张获得。"..
  "<br><br> <font color = '#a40000'>龙跳天门，虎卧凤阙。",
}

local wudaozi = General(extension, "lingling__wudaozi", "tang", 3)
local shenlai = fk.CreateActiveSkill{
  name = "lingling__shenlai",
  anim_type = "support",
  card_num = 2,
  target_num = 1,
  prompt = "#lingling__shenlai",
  expand_pile = function (self)
    return table.filter(Fk:currentRoom():getBanner(self.name), function (id)
      return Fk:currentRoom():getCardArea(id) == Card.Void
    end)
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2
  end,
  card_filter = function(self, player, to_select, selected)
    if #selected == 0 then
      return table.contains(player:getCardIds("he"), to_select) and Fk:getCardById(to_select).color == Card.Black
    elseif #selected == 1 then
      return table.contains(player:getCardIds("he"), selected[1]) and
        table.contains(Fk:currentRoom():getBanner(self.name), to_select) and
        Fk:currentRoom():getCardArea(to_select) == Card.Void
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and #selected_cards == 2 then
      return Fk:currentRoom():getCardArea(selected_cards[2]) == Card.Void and
      Fk:currentRoom():getPlayerById(to_select):hasEmptyEquipSlot(Fk:getCardById(selected_cards[2]).sub_type)
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:recastCard({effect.cards[1]}, player, self.name)
    if target.dead or not target:hasEmptyEquipSlot(Fk:getCardById(effect.cards[2]).sub_type) then return end
    if #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
      return e.data[1].from == player.id and e.data[1].card.trueName == "analeptic"
    end, Player.HistoryRound) == 0 and math.random() < 0.25 then
      room:sendLog{
        type = "#lingling__shenlai_fail",
        from = player.id,
        toast = true,
      }
      return
    end
    room:setCardMark(Fk:getCardById(effect.cards[2]), MarkEnum.DestructOutEquip, 1)
    room:moveCardIntoEquip(target, effect.cards[2], self.name, false, player.id)
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    local cards = U.prepareDeriveCards(room, {
      {"lingling__gods_painting", Card.Spade, 2},
      {"lingling__jialing_river", Card.Spade, 2},
      {"lingling__buddha_born", Card.Spade, 2},
      {"lingling__inferno", Card.Spade, 2},
      {"lingling__vimalakirti", Card.Spade, 2},
      {"lingling__door_god", Card.Spade, 2},
      {"lingling__paint_zhongkui", Card.Spade, 2},
      {"lingling__paint_guanyin", Card.Spade, 2},
    }, self.name)
    room:setBanner(self.name, cards)
  end,
}
local jinwu = fk.CreateTriggerSkill{
  name = "lingling__jinwu",

  on_acquire = function (self, player, is_start)
    player.room:addPlayerEquipSlots(player, { Player.TreasureSlot })
  end,
  on_lose = function (self, player, is_death)
    player.room:abortPlayerArea(player, { Player.TreasureSlot })
  end,
}
local huanjiu = fk.CreateTriggerSkill{
  name = "lingling__huanjiu",
  anim_type = "support",
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and #target:getCardIds("he") > 1
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForDiscard(target, 2, 2, true, self.name, true, nil, "#lingling__huanjiu-invoke:"..player.id, true)
    if #cards == 2 then
      self.cost_data = {tos = {player.id}, cards = cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, target, target)
    if player.dead then return end
    local card = room:getCardsFromPileByRule("analeptic", 1, "allPiles")
    if #card > 0 then
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, target.id)
      if player.dead then return end
      card = Fk:getCardById(card[1])
      if table.contains(player:getCardIds("h"), card.id) and player:canUseTo(card, player, {bypass_times = true}) and
        room:askForSkillInvoke(player, self.name, nil, "#lingling__huanjiu-use:::"..card:toLogString()) then
        room:useCard({
          from = player.id,
          tos = {{player.id}},
          card = card,
          extraUse = true,
        })
        if player.dead then return end
      end
    end
    room:askForUseActiveSkill(player, "lingling__shenlai", "#lingling__shenlai", true)
  end,
}
wudaozi:addSkill(shenlai)
wudaozi:addSkill(jinwu)
wudaozi:addSkill(huanjiu)
Fk:loadTranslationTable{
  ["lingling__wudaozi"] = "吴道子",
  ["#lingling__wudaozi"] = "穷尽丹青",
  ["illustrator:lingling__wudaozi"] = "珊瑚虫",
  ["designer:lingling__wudaozi"] = "伶",

  ["lingling__shenlai"] = "神来",
  [":lingling__shenlai"] = "出牌阶段限两次，你可以选择以下一张牌，重铸一张黑色牌，令一名对应装备栏空余的角色装备之：<br>"..
  "<a href=':lingling__gods_painting'>【八十七神仙卷】</a><br>"..
  "<a href=':lingling__jialing_river'>【嘉陵江三百里】</a><br>"..
  "<a href=':lingling__buddha_born'>【送子天王图】</a><br>"..
  "<a href=':lingling__inferno'>【地狱变相图】</a><br>"..
  "<a href=':lingling__vimalakirti'>【维摩诘经变图】</a><br>"..
  "<a href=':lingling__door_god'>【门神】</a><br>"..
  "<a href=':lingling__paint_zhongkui'>【钟馗】</a><br>"..
  "<a href=':lingling__paint_guanyin'>【观音】</a>。<br>"..
  "每种限有一张，离开装备区时销毁之。若你本回合未使用【酒】，此技能有25%几率作画失败。",
  ["lingling__jinwu"] = "金屋",
  [":lingling__jinwu"] = "你有两个宝物栏。（不会同时显示，点击头像可查看已装备宝物）",
  ["lingling__huanjiu"] = "换酒",
  [":lingling__huanjiu"] = "其他角色回合开始时，其可以弃置两张牌令你获得一张【酒】，你可以使用之，且你可以发动〖神来〗。"..
  "<br><br> <font color = '#a40000'>一日嘉陵江，半生笼中雀。",
  ["#lingling__shenlai"] = "神来：你可以作画，选择重铸的一张黑色牌和置入的装备，再选择置入装备的目标（右键/长按可查看装备效果）",
  ["#lingling__shenlai_fail"] = "无酒助兴，%from 作画失败了…",
  ["#lingling__huanjiu-invoke"] = "换酒：是否弃两张牌，令 %src 获得一张【酒】且其可以发动“神来”？",
  ["#lingling__huanjiu-use"] = "换酒：是否使用这张%arg？",
}

local zhongkui = General(extension, "lingling__zhongkui", "god", 5)
local yaofen = fk.CreateTriggerSkill{
  name = "lingling__yaofen",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.GameStart, fk.EnterDying, fk.DrawNCards, fk.TurnEnd, fk.PreHpRecover},
  can_trigger = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player:hasSkill(self)
    elseif target == player and not player.dead and table.find(player.room.players, function (p)
      return p:hasSkill(self)
    end) then
      if event == fk.EnterDying then
        if player:getMark("@@lingling__ghost") == 0 then
          local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
          return turn_event and turn_event.data[1] == player
        end
      elseif player:getMark("@@lingling__ghost") > 0 then
        if event == fk.DrawNCards then
          return true
        elseif event == fk.TurnEnd then
          return math.random() < 0.5
        elseif event == fk.PreHpRecover then
          return math.random() < 0.6
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
      for _, p in ipairs(room:getAlivePlayers()) do
        room:handleAddLoseSkills(p, "lingling__quantai", nil, true, false)
      end
    elseif event == fk.EnterDying then
      if player.dead then return end
      if player:isWounded() then
        room:recover{
          who = player,
          num = player.maxHp - player.hp,
          skillName = self.name,
        }
        if player.dead then return end
      end
      if player:getHandcardNum() < 4 then
        player:drawCards(4 - player:getHandcardNum(), self.name)
        if player.dead then return end
      end
      player:reset()
      if player.dead then return end
      room:setPlayerMark(player, "@@lingling__ghost", 1)
    elseif event == fk.DrawNCards then
      data.n = data.n + 2
    elseif event == fk.TurnEnd then
      room:loseHp(player, 1, self.name)
    elseif event == fk.PreHpRecover then
      return true
    end
  end,
}
local zhuogui = fk.CreateActiveSkill{
  name = "lingling__zhuogui",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhuogui",
  interaction = UI.ComboBox {choices = {"lingling__zhuogui1", "lingling__zhuogui2", "lingling__zhuogui3"}},
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self, player, to_select, selected)
    if #selected == 0 then
      local target = Fk:currentRoom():getPlayerById(to_select)
      if self.interaction.data == "lingling__zhuogui1" then
        return not target.chained
      elseif self.interaction.data == "lingling__zhuogui2" then
        if target.chained then
          if to_select == player.id then
            return #player:getCardIds("e") > 0
          else
            return not target:isNude()
          end
        end
      elseif self.interaction.data == "lingling__zhuogui3" then
        return target.chained
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if target:getMark("@@lingling__ghost") > 0 and player:getMark("lingling__zhuogui-turn") == 0 then
      room:setPlayerMark(player, "lingling__zhuogui-turn", 1)
      player:setSkillUseHistory(self.name, 0, Player.HistoryPhase)
    end
    if self.interaction.data == "lingling__zhuogui1" then
      target:setChainState(true)
    elseif self.interaction.data == "lingling__zhuogui2" then
      local card
      if target == player and #player:getCardIds("e") > 0 then
        card = room:askForCardChosen(player, player, "e", self.name, "#lingling__zhuogui-prey::"..player.id)
      elseif target ~= player and not target:isNude() then
        card = room:askForCardChosen(player, target, "he", self.name, "#lingling__zhuogui-prey::"..target.id)
      end
      if card then
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    elseif self.interaction.data == "lingling__zhuogui3" then
      room:damage {
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
        damageType = fk.ThunderDamage,
      }
    end
  end,
}
local quantai = fk.CreateActiveSkill{
  name = "lingling__quantai",
  anim_type = "big",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__quantai",
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:getMark("@@lingling__ghost") == 0 and player.hp > 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:loseHp(player, player.hp, self.name)
  end,
}
local quantai_quote = fk.CreateActiveSkill{
  name = "lingling__quantai_quote",
}
Fk:addSkill(quantai)
zhongkui:addSkill(yaofen)
zhongkui:addSkill(zhuogui)
zhongkui:addRelatedSkill(quantai_quote)
Fk:loadTranslationTable{
  ["lingling__zhongkui"] = "钟馗",
  ["#lingling__zhongkui"] = "驱魔帝君",
  ["illustrator:lingling__zhongkui"] = "珊瑚虫",
  ["designer:lingling__zhongkui"] = "伶",

  ["lingling__yaofen"] = "妖氛",
  [":lingling__yaofen"] = "游戏开始时，所有角色获得技能〖泉台〗。当一名没有“鬼”标记的角色于其回合内濒死时，其：回复所有体力，摸牌至四张，"..
  "重置武将牌状态、获得“鬼”标记。有“鬼”标记的角色摸牌阶段多摸两张牌、回合结束时50%几率失去1点体力、回复体力时60%几率防止之。",
  ["lingling__zhuogui"] = "捉鬼",
  [":lingling__zhuogui"] = "出牌阶段限一次，你可以选择一项：横置一名角色；获得一名横置角色一张牌；对一名横置角色造成1点雷电伤害。"..
  "若其为有“鬼”标记的角色，重置此技能（每回合限重置一次）。",
  ["lingling__quantai"] = "泉台",
  [":lingling__quantai"] = "出牌阶段，若你没有“鬼”标记，你可以失去所有体力。",
  ["lingling__quantai_quote"] = "泉台",
  [":lingling__quantai_quote"] = "出牌阶段，若你没有“鬼”标记，你可以失去所有体力。"..
  "<br><br> <font color = '#a40000'>驱邪逐鬼，恶灵退散。",
  ["@@lingling__ghost"] = "鬼",
  ["#lingling__zhuogui"] = "捉鬼：你可以执行一项",
  ["lingling__zhuogui1"] = "横置一名角色",
  ["lingling__zhuogui2"] = "获得一名横置角色一张牌",
  ["lingling__zhuogui3"] = "对一名横置角色造成1点雷电伤害",
  ["#lingling__zhuogui-prey"] = "捉鬼：获得 %dest 一张牌",
  ["#lingling__quantai"] = "泉台：你可以失去所有体力变为鬼！",

  ["$lingling__quantai1"] = "待到泉台招旧部，旌旗十万斩阎罗。",
  ["$lingling__quantai2"] = "待到泉台招旧部，旌旗十万斩阎罗。",
}

local laozi = General(extension, "lingling__lier", "qun", 4)
laozi.total_hidden = true
local daoqiqingniu = fk.CreateDistanceSkill{
  name = "lingling__daoqiqingniu",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if to:hasSkill(self) then
      return 1
    end
    return 0
  end,
}
laozi:addSkill(daoqiqingniu)
Fk:loadTranslationTable{
  ["lingling__lier"] = "老子",
  ["#lingling__lier"] = "太上老君",
  ["illustrator:lingling__lier"] = "珊瑚虫",
  ["designer:lingling__lier"] = "伶",

  ["lingling__tiaodaoyouque"] = "天道有缺",
  [":lingling__tiaodaoyouque"] = "其他角色对你使用的牌、你对其他角色使用的牌皆延后到你下回合开始时结算，且届时你从这两种时机的非装备牌中"..
  "各选择一张结算两次。",
  ["lingling__daoqiqingniu"] = "倒骑青牛",
  [":lingling__daoqiqingniu"] = "其他角色计算与你的距离+1。"..
  "<br><br> <font color = '#a40000'>人法地，地法天，天法道，道法自然。",
}

local zhuangzi = General(extension, "lingling__zhuangzhou", "qun", 3)
local WhoAmI = fk.CreateTriggerSkill{
  name = "lingling__WhoAmI",
  anim_type = "support",
  frequency = Skill.Compulsory,
  priority = {
    [fk.GameStart] = 1,
    [fk.TurnEnd] = 2,
  },
  events = {fk.GameStart, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.GameStart then
        return true
      elseif event == fk.TurnEnd then
        return target:getMark("@@lingling_me") > 0 and
          not table.contains({target.general, target.deputyGeneral}, "lingling__zhuangzhou") and
          math.random() < 0.5
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      room:setPlayerMark(player, "@@lingling_me", 1)
    elseif event == fk.TurnEnd then
      local general = target.general
      room:changeHero(target, "lingling__zhuangzhou", false, false, true, false, false)
      for _, p in ipairs(room:getAlivePlayers()) do
        if p:getMark("@@lingling_me") == 0 and table.contains({p.general, p.deputyGeneral}, "lingling__zhuangzhou") then
          room:changeHero(p, general, false, false, true, false, false)
        end
      end
    end
  end,
}
local ButterflyIsMe = fk.CreateTriggerSkill{
  name = "lingling__ButterflyIsMe",
  anim_type = "masochism",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@@lingling_me") > 0 and data.from and data.from ~= player
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:changeHero(player, data.from.general, false, false, true, false, false)
    room:changeHero(data.from, "lingling__zhuangzhou", false, false, true, false, false)
  end,
}
local IAmButter = fk.CreateTriggerSkill{
  name = "lingling__IAmButter",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    for _, p in ipairs(room:getAlivePlayers()) do
      if not p.dead and p:getMark("@@lingling_me") > 0 then
        p:drawCards(2, self.name)
      end
    end
  end,

  refresh_events = {fk.RoundStart},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self) and player.room:getBanner("RoundCount") > 6
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    player.dead = true
    player._splayer:setDied(true)
    local deathStruct = {who = player.id}
    local logic = room.logic
    logic:trigger(fk.BeforeGameOverJudge, player, {who = player.id})
    room:sendLogEvent("Death", {to = player.id})
    room:setPlayerProperty(player, "role_shown", true)
    --room:broadcastProperty(player, "dead")
    player.drank = 0
    room:broadcastProperty(player, "drank")
    player.shield = 0
    room:broadcastProperty(player, "shield")
    logic:trigger(fk.GameOverJudge, player, deathStruct)
    logic:trigger(fk.Death, player, deathStruct)
    player:bury()
    logic:trigger(fk.Deathed, player, deathStruct)
    room:changeHero(player, "lingling__butterfly", false, false, false, false, false)
    room:notifySkillInvoked(player, self.name, "big")
  end,
}
zhuangzi:addSkill(WhoAmI)
zhuangzi:addSkill(ButterflyIsMe)
zhuangzi:addSkill(IAmButter)
local butterfly = General(extension, "lingling__butterfly", "qun", 3)
butterfly.total_hidden = true
Fk:loadTranslationTable{
  ["lingling__zhuangzhou"] = "庄子",
  ["lingling__butterfly"] = "蝴蝶",
  ["#lingling__zhuangzhou"] = "天地逍遥",
  ["illustrator:lingling__zhuangzhou"] = "珊瑚虫",
  ["designer:lingling__zhuangzhou"] = "伶",

  ["lingling__WhoAmI"] = "我是谁",
  [":lingling__WhoAmI"] = "游戏开始时，你获得“我”标记。有“我”标记的角色回合结束时，若其不是庄子，其有50%几率变成庄子，然后若存在没有“我”"..
  "标记的庄子，其变成因“蝴蝶是我”变成庄子前的武将。",
  ["lingling__ButterflyIsMe"] = "蝴蝶是我",
  [":lingling__ButterflyIsMe"] = "当你受到伤害后，若你有“我”标记，你将武将变成伤害来源的武将，其变成庄子。",
  ["lingling__IAmButter"] = "我是蝴蝶",
  [":lingling__IAmButter"] = "回合结束时，你摸一张牌，然后有“我”标记的角色摸两张牌。第七轮开始时，你飞走，离开游戏。"..
  "<br><br> <font color = '#a40000'>外忘于物，内忘于我。",
  ["@@lingling_me"] = "我",

  ["$lingling__IAmButter1"] = "飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞~",
  ["$lingling__IAmButter2"] = "飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞飞~",
}

local jiangshang = General(extension, "lingling__jiangziya", "qun", 3)
local ol__puyuan_derivecards = {
  {"py_halberd", Card.Diamond, 12},
  {"py_blade", Card.Spade, 5},
  {"blood_sword", Card.Spade, 6},
  {"py_double_halberd", Card.Diamond, 13},
  {"black_chain", Card.Spade, 13},
  {"five_elements_fan", Card.Diamond, 1},
  {"py_belt", Card.Spade, 2},
  {"py_robe", Card.Club, 1},
  {"py_cloak", Card.Spade, 9},
  {"py_diagram", Card.Spade, 2},
  {"breastplate", Card.Club, 1},
  {"dark_armor", Card.Club, 2},
  {"py_hat", Card.Diamond, 1},
  {"py_coronet", Card.Club, 4},
  {"py_threebook", Card.Spade, 5},
  {"py_mirror", Card.Diamond, 1},
  {"wonder_map", Card.Club, 12},
  {"taigong_tactics", Card.Spade, 1}
}
local majun_derivecards = {
  {"ex_crossbow", Card.Club, 1},
  {"ex_eight_diagram", Card.Spade, 2},
  {"ex_nioh_shield", Card.Club, 2},
  {"ex_silver_lion", Card.Club, 1},
  {"ex_vine", Card.Spade, 2}
}
local zhuren_derivecards = {
  {"red_spear", Card.Heart, 1},
  {"quenched_blade", Card.Diamond, 1},
  {"poisonous_dagger", Card.Spade, 1},
  {"water_sword", Card.Club, 1},
  {"thunder_blade", Card.Spade, 1}
}
local diaoyu = fk.CreateTriggerSkill{
  name = "lingling__diaoyu",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.TurnStart, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
    local rand = math.random(5)
    if rand == 1 then
      if player:hasSkill("zaowang", true) then
        local all_skills = table.filter(player:getTableMark("lingling__diaoyu1_skills"), function (s)
          return player:hasSkill(s, true)
        end)
        if math.random() < 0.25 then
          local targets = {}
          for _, p in ipairs(room:getOtherPlayers(player)) do
            if table.find(p.player_skills, function (s)
              return s.visible and s:isPlayerSkill(p) and not player:hasSkill(s, true)
            end) then
              table.insert(targets, p)
            end
          end
          if #targets > 0 then
            local to = table.random(targets)
            room:doIndicate(player.id, {to.id})
            local skills = {}
            for _, s in ipairs(to.player_skills) do
              if s.visible and s:isPlayerSkill(p) and not player:hasSkill(s, true) then
                table.insert(skills, s.name)
              end
            end
            local skill = table.random(skills)
            if #all_skills > 2 then
              room:handleAddLoseSkills(player, "-"..table.random(all_skills), nil, true, false)
            end
            table.insert(all_skills, skill)
            room:handleAddLoseSkills(player, skill, nil, true, false)
            room:handleAddLoseSkills(to, "-"..skill, nil, true, false)
          end
        else
          local skills = {}
          for _, general in pairs(Fk.generals) do
            if not general.hidden and not general.total_hidden then
              table.insertTableIfNeed(skills, general:getSkillNameList(true))
            end
          end
          skills = table.filter(skills, function (s)
            return not player:hasSkill(s, true)
          end)
          if #skills > 0 then
            local skill = table.random(skills)
            if #all_skills > 2 then
              room:handleAddLoseSkills(player, "-"..table.random(all_skills), nil, true, false)
            end
            table.insert(all_skills, skill)
            room:handleAddLoseSkills(player, skill, nil, true, false)
          end
        end
        room:setPlayerMark(player, "lingling__diaoyu1_skills", all_skills)
      else
        room:handleAddLoseSkills(player, "zaowang", nil, true, false)
      end
    elseif rand == 2 then
      local cards = {}
      if math.random() < 0.5 then
        cards = table.filter(U.prepareDeriveCards(room, ol__puyuan_derivecards, "lingling__diaoyu1"), function (id)
          return not table.contains({Card.Unknown, Card.PlayerJudge, Card.PlayerSpecial, Card.Processing}, room:getCardArea(id))
        end)
      elseif math.random() < 0.5 then
        cards = table.filter(U.prepareDeriveCards(room, majun_derivecards, "lingling__diaoyu2"), function (id)
          return not table.contains({Card.Unknown, Card.PlayerJudge, Card.PlayerSpecial, Card.Processing}, room:getCardArea(id))
        end)
      else
        cards = table.filter(U.prepareDeriveCards(room, zhuren_derivecards, "lingling__diaoyu3"), function (id)
          return not table.contains({Card.Unknown, Card.PlayerJudge, Card.PlayerSpecial, Card.Processing}, room:getCardArea(id))
        end)
      end
      if #cards > 0 then
        local id = table.random(cards)
        room:moveCardTo(id, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, true, player.id)
        if not player.dead and table.contains(player:getCardIds("h"), id) then
          local card = Fk:getCardById(id)
          if room:askForSkillInvoke(player, self.name, nil, "#lingling__diaoyu-recast:::"..card:toLogString()) then
            room:recastCard({id}, player, self.name)
          else
            local to = player
            if #room:getOtherPlayers(player) > 0 then
              to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
                "#lingling__diaoyu-give:::"..card:toLogString(), self.name, true)
              if #to > 0 then
                to = room:getPlayerById(to[1])
              else
                to = player
              end
            end
            if to ~= player then
              room:moveCardTo(id, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, true, player.id)
            end
            if not to.dead and table.contains(to:getCardIds("h"), id) and to:canUseTo(card, to) and
              room:askForSkillInvoke(to, self.name, nil, "#lingling__diaoyu-use:::"..card:toLogString()) then
              room:useCard({
                from = to.id,
                tos = {{to.id}},
                card = card,
              })
            end
          end
        end
      else
        room:sendLog{
          type = "#lingling__diaoyu",
          from = player.id,
          toast = true,
        }
      end
    elseif rand == 3 then
      if player:getMark("@@dawu") + player:getMark("@@jieying_camp") > 0 then
        room:sendLog{
          type = "#lingling__diaoyu",
          from = player.id,
          toast = true,
        }
      else
        room:setPlayerMark(player, "lingling__diaoyu_dawu", 1)
        room:setPlayerMark(player, "lingling__diaoyu_dawu-turn", 1)
        if player:getMark("@@dawu") == 0 then
          room:setPlayerMark(player, "@@dawu", 1)
          room:addTableMark(player, "_ling__dawu", player.id)
        end
        if player:getMark("@@jieying_camp") == 0 then
          room:setPlayerMark(player, "@@jieying_camp", 1)
        end
        room:handleAddLoseSkills(player, "lingling__dawu", nil, true, false)
        room:handleAddLoseSkills(player, "lingling__jieying", nil, true, false)
      end
    elseif rand == 4 and player:getMark("lingling__diaoyu_maxHp") == 0 then
      room:changeMaxHp(player, 1)
      if player:isWounded() and not player.dead then
        room:recover{
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
      if player.maxHp > 5 and not player.dead then
        room:setPlayerMark(player, "lingling__diaoyu_maxHp", 1)
      end
    else
      room:sendLog{
        type = "#lingling__diaoyu",
        from = player.id,
        toast = true,
      }
    end
  end,

  refresh_events = {fk.TurnEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("lingling__diaoyu_dawu") - player:getMark("lingling__diaoyu_dawu-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local n = player:getMark("lingling__diaoyu_dawu") - player:getMark("lingling__diaoyu_dawu-turn")
    room:removePlayerMark(player, "lingling__diaoyu_dawu", n)
    room:handleAddLoseSkills(player, "-lingling__dawu", nil, true, false)
    room:handleAddLoseSkills(player, "-lingling__jieying", nil, true, false)
  end,
}
local dawu = fk.CreateTriggerSkill{
  name = "lingling__dawu",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target:getMark("@@dawu") > 0 and
      data.damageType ~= fk.ThunderDamage and table.contains(player:getTableMark("_ling__dawu"), target.id)
  end,
  on_cost = Util.TrueFunc,
  on_use = Util.TrueFunc,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("_ling__dawu") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(player:getTableMark("_ling__dawu")) do
      local p = room:getPlayerById(id)
      room:removePlayerMark(p, "@@dawu", 1)
    end
    room:setPlayerMark(player, "_ling__dawu", 0)
    room:handleAddLoseSkills(player, "-lingling__dawu", nil, true, false)
  end,

  on_lose = function (self, player, is_death)
    local room = player.room
    for _, id in ipairs(player:getTableMark("_ling__dawu")) do
      local p = room:getPlayerById(id)
      room:removePlayerMark(p, "@@dawu", 1)
    end
  end,
}
local jieying = fk.CreateTriggerSkill{
  name = "lingling__jieying",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart, fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player:getMark("@@jieying_camp") > 0 then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Finish
      elseif event == fk.DrawNCards then
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    self.cost_data = nil
    if event == fk.EventPhaseStart then
      local room = player.room
      local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
        "#lingling__jieying-choose", self.name, true)
      if #to > 0 then
        self.cost_data = {tos = to}
        return true
      end
    elseif event == fk.DrawNCards then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      player.room:handleAddLoseSkills(player, "-lingling__jieying", nil, true, false)
    elseif event == fk.DrawNCards then
      data.n = data.n + 1
    end
  end,

  on_lose = function (self, player, is_death)
    local room = player.room
    if table.every(room.alive_players, function (p)
      return not p:hasSkill(self, true)
    end) then
      for _, p in ipairs(room.alive_players) do
        room:setPlayerMark(p, "@@jieying_camp", 0)
      end
    end
  end,
}
local jieying_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__jieying_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@@jieying_camp") > 0 and scope == Player.HistoryPhase then
      return #table.filter(Fk:currentRoom().alive_players, function (p) return p:hasSkill(jieying) end)
    end
  end,
}
local jieying_maxcards = fk.CreateMaxCardsSkill{
  name = "#lingling__jieying_maxcards",
  correct_func = function(self, player)
    if player:getMark("@@jieying_camp") > 0 then
      return #table.filter(Fk:currentRoom().alive_players, function (p) return p:hasSkill(jieying) end)
    else
      return 0
    end
  end,
}
Fk:loadTranslationTable{
  ["lingling__diaoyu"] = "钓鱼",
  [":lingling__diaoyu"] = "回合开始时和回合结束时，你随机获得以下一项："..
  "<br>1.一个随机技能，若你没有〖造王〗则获得〖造王〗，若你有〖造王〗则25%几率为场上随机一名其他角色的随机一个技能，且其失去该技能。"..
  "若你除〖造王〗外获得了至少三个技能，你获得技能前随机失去一个除〖造王〗外以此法获得的技能。"..
  "<br>2.一个装备牌，25%几率为马钧强化的装备牌，25%几率为蒲元打造的装备牌，50%几率为神武装备牌，你任意分配此牌或重铸，获得此牌的角色可以使用。"..
  "<br>3.两个标记，“大雾”和“营”，你下回合结束时失去，且视为拥有对应技能直到失去该标记。"..
  "<br>4.1点体力上限和1点体力，然后若你体力上限不少于5点，删去该项。"..
  "<br>5.空军了，哥们。",
  ["lingling__dawu"] = "大雾",
  [":lingling__dawu"] = "结束阶段开始时，你可以将至少一张“星”置入弃牌堆并选择等量的角色，当其于你的下回合开始之前受到不为雷电伤害的伤害时，"..
  "防止此伤害。",
  ["lingling__jieying"] = "劫营",
  [":lingling__jieying"] = "回合开始时，若没有角色有“营”标记，你获得一个“营”标记；结束阶段你可以将“营”标记交给一名其他角色；"..
  "有“营”的角色摸牌阶段多摸一张牌、使用【杀】的次数上限+1、手牌上限+1。有“营”的其他角色的结束阶段，你获得其“营”标记及所有手牌。"..
  "<br><br> <font color = '#a40000'>文王拉车八百步，周朝天下八百年。",
  ["#lingling__diaoyu-lose"] = "钓鱼：钓到的技能太多啦！你即将获得“%arg”，需要先失去一个现有技能",
  ["#lingling__diaoyu-recast"] = "钓鱼：你可以重铸这张%arg",
  ["#lingling__diaoyu-give"] = "钓鱼：你可以将这张%arg交给其他角色",
  ["#lingling__diaoyu-use"] = "钓鱼：你可以使用这张%arg",
  ["#lingling__jieying-choose"] = "劫营：你可将“营”标记交给其他角色",
  ["#lingling__diaoyu"] = " %from 钓鱼空军了…",
}

return extension
